package com.maserb.monitor.dataCenter.handler;

import com.maserb.monitor.common.AjaxResult;
import com.maserb.monitor.common.AjaxUtils;
import com.maserb.monitor.common.Func_T;
import com.maserb.monitor.dataCenter.communication.*;
import com.maserb.monitor.dataCenter.model.EigenValueRequest;
import com.maserb.monitor.dataCenter.model.EigenValueRequestKey;
import com.maserb.monitor.dataCenter.model.EigenValueResponse;
import com.maserb.monitor.dataCenter.model.EigenValueResponseResult;
import com.maserb.monitor.entity.EigenValueEntity;
import com.maserb.monitor.repository.EigenValueRepository;
import com.maserb.monitor.repository.WaveRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class EigenValueRepositoryHandler {
    private ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4);

    @Autowired
    private EigenValueRepository eigenValueRepository;
    @Autowired
    private AlarmRepositoryHandler alarmRepositoryHandler;

    public void publish(EigenValueNetPackage response) {
        fixedThreadPool.execute(() -> {
            try {
                if (response.getEigenvalueRecords() != null) {
                    for (EigenValueRecord record : response.getEigenvalueRecords()) {
                        EigenValueEntity entity = new EigenValueEntity();
                        entity.setDeviceCode(response.getDeviceCode());
                        entity.setPointCode(record.getPointCode());
                        entity.setSampleTime(new Date(record.getSampleTime().toDate().getTime()));
                        List<EigenWarningStatusEnum> statuses = new LinkedList<>();
                        if (record.getEigenValueList() != null) {
                            for (int i = 0; i < record.getEigenValueList().size(); i++) {
                                EigenValue ev = record.getEigenValueList().get(i);
                                entity.setValueAndStatusX(i, ev.getValueType(), ev.getWarningStatusEnum(), ev.getEigenValue());
                                statuses.add(ev.getWarningStatusEnum());
                            }
                        }
                        eigenValueRepository.save(entity, response.getDeviceCode());
                        alarmRepositoryHandler.publish(entity, statuses, response.getDeviceCode());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
